﻿using UnityEngine;
using System.Collections;

namespace Lost{
	/// <summary>
	/// 可抓取物品
	/// </summary>
	public class CatchableItem : InteractiveItem {
		[SerializeField] string targetName = "RightHand";
		Transform targetTran;
		///跟随运动时，限制本地方向的移动
		[SerializeField] Vector3 limitMoveDir = new Vector3(1f,1f,1f);
		[SerializeField] bool limitRotation = false;

		Coroutine curCor;

		public override void Interact (HitInf hitInf)
		{
			if (!IsInteractive) {
				return;
			}
			if (targetTran == null) {
				targetTran = ItemsManager.FindTransform (targetName);
			}
			if (curCor == null) {
				curCor = StartCoroutine (MoveWithTarget (targetTran));
			}
		}
		IEnumerator MoveWithTarget(Transform tr){
			Rigidbody rb = GetComponent<Rigidbody> ();
			bool useGravity = false;
			if (rb != null) {
				useGravity = rb.useGravity;
				rb.useGravity = false;
			}
			//暂时改变父节点
			Transform preParent = tr.parent;
			tr.parent = null;

			Vector3 prePos = tr.position;
			Quaternion preRotation = tr.rotation;
			while (!LostInput.GetInputEvent (InputEvent.Release)) {
				//位置跟随
				Vector3 moveDir = tr.position - prePos;
				Debug.Log (moveDir);
				moveDir = new Vector3 (Vector3.Dot (moveDir, transform.right) * limitMoveDir.x, 
					Vector3.Dot (moveDir, transform.up) * limitMoveDir.y, Vector3.Dot (moveDir, transform.forward) * limitMoveDir.z);
				transform.Translate (moveDir);
				prePos = tr.position;
				//旋转跟随
				if(!limitRotation){
					Quaternion diffRot = tr.rotation * Quaternion.Euler(-preRotation.eulerAngles);
					transform.rotation *= diffRot;
				}
				preRotation = tr.rotation;
				yield return null;
			}

			if (rb != null) {
				rb.useGravity = useGravity;
			}
			tr.parent = preParent;
			curCor = null;
		}
	}
}
